
package com.code.entity.generator;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.code.constant.SqlConstant;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DictGenerator {
    static String PATH = "";
    static String PREFIX_DIR = File.separator + "script" + File.separator;

    static String PATH_DICT_EXCEL = "t_dict.xls";
    static String COMMON_FILE_NAME = "7.dictData.sql";

    static String VERSION_FILE_PATH = "data/script/seperatebycustomer/";

    static String INSERT_DICT = "INSERT INTO `t_dict`( `parent_code`, `code`, `name`, `value`, `status`, `sort`, `deleted`, `remark`) " +
            "VALUES (";
    static String INSERT_END = ");\n";

    static String DELETE_DICT = "\ndelete from `t_dict` where `parent_code`='";
    static String DELETE_DICT_END = "';\n";

    public static String getDeleteDictByParentCode(String code) {
        return DELETE_DICT + code + DELETE_DICT_END;
    }

    public static String getDictInsertSql(List<Dict> dictList) {
        StringBuilder sb = new StringBuilder();
        sb.append(getTruncateSql("t_dict"));
        dictList.forEach(dict -> {
            if (!dict.getIsDefault().equals("0")) {
                return;
            }
            sb.append(INSERT_DICT);
            sb.append("'").append(dict.getParentCode()).append("'").append(",");
            sb.append("'").append(dict.getCode()).append("'").append(",");
            sb.append("'").append(dict.getName()).append("'").append(",");
            sb.append("'").append(dict.getValue()).append("'").append(",");
            sb.append("'").append(dict.getStatus()).append("'").append(",");
            sb.append("'").append(dict.getSort()).append("'").append(",");
            sb.append("'").append(dict.getDeleted()).append("'").append(",");
            sb.append("'").append(dict.getRemark()).append("'");
            sb.append(INSERT_END);

        });
        return sb.toString().replaceAll("'null'", "NULL");
    }


    public static void main(String[] args) throws IOException {
        generate();
    }


    private static String getTruncateSql(String tableName) {
        return "truncate table " +
                tableName +
                ";\n";
    }

    private static Map<String, String> getCustomerDict(List<Dict> dictList) {
        Map<String, String> fileSqlMap = new HashMap<>();
        String allVersion = dictList.get(0).getAllVersion();
        String[] versions = allVersion.split("-");
        for (int i = 0; i < versions.length; i++) {
            String version = versions[i];
            String fileName = "9.dict_" + version;

            Map<String, String> parentCodeMap = new HashMap();
            StringBuilder sb = new StringBuilder();
            dictList.forEach(dict -> {
                if (StringUtils.isBlank(dict.getVersion()) || StringUtils.isBlank(dict.getParentCode())) {
                    return;
                }
                if (!parentCodeMap.containsKey(dict.getParentCode())) {
                    if (StringUtils.isNotBlank(dict.getParentCode()) && dict.getVersion().contains(version)) {
                        sb.append(getDeleteDictByParentCode(dict.getParentCode()));
                        parentCodeMap.put(dict.getParentCode(), "1");
                    }

                }
                if (StringUtils.isNotBlank(dict.getVersion())
                        && StringUtils.isNotBlank(dict.getParentCode())
                        && dict.getVersion().contains(version)) {
                    sb.append(INSERT_DICT);
                    sb.append("'").append(dict.getParentCode()).append("'").append(",");
                    sb.append("'").append(dict.getCode()).append("'").append(",");
                    sb.append("'").append(dict.getName()).append("'").append(",");
                    sb.append("'").append(dict.getValue()).append("'").append(",");
                    sb.append("'").append(dict.getStatus()).append("'").append(",");
                    sb.append("'").append(dict.getSort()).append("'").append(",");
                    sb.append("'").append(dict.getDeleted()).append("'").append(",");
                    sb.append("'").append(dict.getRemark()).append("'");
                    sb.append(INSERT_END);
                }
            });
            fileSqlMap.put(fileName, sb.toString().replaceAll("'null'", "NULL"));
        }


        return fileSqlMap;
    }


    public static void generate() {
        //先获取文件绝对路径
        getAbsolutePath();


        String dir = PATH + PATH_DICT_EXCEL;
        File file = new File(dir);
        ImportParams params = new ImportParams();
        List<Dict> dictList = ExcelImportUtil.importExcel(file, Dict.class, params);
        String commonSql = getDictInsertSql(dictList);
        Map<String, String> customerSql = getCustomerDict(dictList);

        //设置输出文件的编码为utf-8
        try {
            File commonSqlFile = new File(PATH + COMMON_FILE_NAME);
            if (commonSqlFile.exists()) {
                commonSqlFile.delete();
            }
            commonSqlFile = new File(PATH + COMMON_FILE_NAME);
            commonSqlFile.createNewFile();

            PrintWriter pfp = new PrintWriter(commonSqlFile, "UTF-8");
            pfp.print(SqlConstant.mysqlUseDb);
            pfp.print(commonSql);
            pfp.flush();
            System.out.println("生成通用字典完成，共：" + dictList.size() + "条数据");

            customerSql.forEach((k, v) -> {
                File file1 = new File(VERSION_FILE_PATH + k + ".sql");
                if (file1.exists()) {
                    file1.delete();
                }
                file1 = new File(VERSION_FILE_PATH + k + ".sql");
                try {
                    file1.createNewFile();
                    PrintWriter pfp1 = new PrintWriter(file1, "UTF-8");
                    pfp1.print(SqlConstant.mysqlUseDb);
                    pfp1.print(v);
                    pfp1.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("单拎字典" + k + "{}完成");
            });
            System.out.println("生成单拎字典完成，共：" + customerSql.size() + "个单独脚本");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void getAbsolutePath() {
        //打包时路径
        PATH = System.getProperty("user.dir");
        System.out.println("=======当前目录 " + PATH);
        PATH = PATH.substring(0, PATH.lastIndexOf(File.separator)) + PREFIX_DIR;
        System.out.println("=======PATH:" + PATH);
        VERSION_FILE_PATH = PATH + "seperatebycustomer" + File.separator;
        System.out.println("=======VERSION_FILE_PATH:" + VERSION_FILE_PATH);
    }


    static HashMap filelist = new HashMap();
}
